<template>
  <div>
    <el-form :model="searchForm" ref="searchForm" label-width="100px" class="demo-searchForm">
    <el-popover
        placement="top"
        width="1250"
        v-model="visible">
      <div style="width: 1200px;display: flex;flex-wrap: wrap;height: 300px">
        <el-form-item label="ID" prop="ID"><el-input v-model="searchForm.ID" style="width: 200px"/></el-form-item>
        <el-form-item label="柜机编码" prop="machineCode"><el-input v-model="searchForm.machineCode" style="width: 200px"/></el-form-item>
        <el-form-item label="设备型号" prop="isModel"><el-input v-model="searchForm.isModel" style="width: 200px"/></el-form-item>
        <el-form-item label="所在地区" prop="location"><el-input v-model="searchForm.location" style="width: 200px"/></el-form-item>
        <el-form-item label="详细地址" prop="address"><el-input v-model="searchForm.address" style="width: 200px"/></el-form-item>
        <el-form-item label="版本号" prop="systemVersion"><el-input v-model="searchForm.systemVersion" style="width: 200px"/></el-form-item>
        <el-form-item label="柜机状态" prop="machineStatus">
          <el-select v-model="searchForm.machineStatus">
            <el-option label="正常" value="0"></el-option>
            <el-option label="禁用" value="1"></el-option>
            <el-option label="已关机" value="2"></el-option>
            <el-option label="重启中" value="3"></el-option>
            <el-option label="未开通" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="存藏类型" prop="storageStatus">
          <el-select v-model="searchForm.storageStatus" placeholder="全部">
            <el-option label="常温" value="0"></el-option>
            <el-option label="冷藏" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="箱门状态" prop="boxStatus">
          <el-select v-model="searchForm.boxStatus">
            <el-option label="正常" value="0"></el-option>
            <el-option label="异常" value="1"></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="箱格状况" prop="region" style="width: 200px">-->
<!--          <el-select v-model="searchForm.region" placeholder="全部">-->
<!--            <el-option label="区域一" value="1"></el-option>-->
<!--            <el-option label="区域二" value="2"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="安装日期" required >
          <el-date-picker
              v-model="params.date"
              type="daterange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="dateFormat"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="开通日期" required>
            <el-date-picker
                v-model="params.dateTime"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="dateTimeFormat"
            >
            </el-date-picker>
        </el-form-item>
      </div>
      <div style="text-align: right; margin: 0">
        <el-button type="primary" @click="selectList()">搜索</el-button>
        <el-button @click="resetForm('searchForm');selectList()">重置</el-button>
        <el-button type="text" @click="closeSearch()">取消</el-button>
      </div>
    </el-popover>
      <div style="display: flex; margin-left: 10px; width: 1300px; height: 40px; margin-bottom: 50px">
        <el-form-item label="柜机状态" prop="machineStatus">
          <el-select v-model="searchForm.machineStatus">
            <el-option label="柜机状态" value="" selected="selected"></el-option>
            <el-option label="正常" value="0"></el-option>
            <el-option label="禁用" value="1"></el-option>
            <el-option label="已关机" value="2"></el-option>
            <el-option label="重启中" value="3"></el-option>
            <el-option label="未开通" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="箱门状态" prop="boxStatus">
          <el-select v-model="searchForm.boxStatus">
            <el-option label="箱门状态" value="" selected="selected"></el-option>
            <el-option label="正常" value="0"></el-option>
            <el-option label="异常" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.searchObj" placeholder="请输入详细地址/编码/型号/版本号/ID" style="width: 300px"/>
        </el-form-item>
        <el-button icon="el-icon-search" @click="selectList()"></el-button>
        <el-button style="margin-left: 50px" @click="visible = true;">高级搜索</el-button>
        <el-button style="margin-left: 50px" @click="addForm.machineStatus=0;add=true;" type="primary">添加</el-button>
        <el-button style="margin-left: 10px" @click="routerAddMore()" type="primary">批量添加</el-button>
      </div>
    </el-form>
    <el-table
        :data="tableData"
        style="width: 100%"
        >
      <el-table-column label="ID" prop="id" width="120">
        <template slot-scope="scope">
          <!-- 使用padStart方法来确保ID是9位的，如果不足则用0填充 -->
          <el-link :underline="false" @click="handleClick(scope.row.id)" style="color:blue">{{ scope.row.id.toString().padStart(9, '0') }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="柜机编码" prop="machineCode" width="120"/>
      <el-table-column label="所在地区" prop="location" width="200">
        <template slot-scope="scope">
          {{ scope.row.location == null ? '' : scope.row.location.split('-').join('') }}
        </template>
      </el-table-column>
      <el-table-column label="详细地址" prop="address"/>
      <el-table-column label="设备型号" prop="isModel" width="120"/>
      <el-table-column label="箱格" prop="" width="120">
        <template slot-scope="scope">
          <el-link :underline="false" @click="goToBoxDetail(scope.row.id)" style="color:blue">{{ scope.row.useCount==null ?  '0' : scope.row.useCount }}/20</el-link>
        </template>
      </el-table-column>
      <el-table-column label="系统版本" prop="systemVersion" width="120"/>
      <el-table-column label="安装日期" prop="installDate" width="120" :formatter="formatDate"/>
      <el-table-column label="开通时间" prop="openDate" :formatter="formatDateTime"/>
      <el-table-column label="箱门状态" prop="boxStatus" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.boxStatus === 0" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row.boxStatus === 1" type="danger">异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="柜机状态" prop="machineStatus" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.machineStatus === 0" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row.machineStatus === 1" type="danger">已禁用</el-tag>
          <el-tag v-else-if="scope.row.machineStatus === 2" type="warning">已关机</el-tag>
          <el-tag v-else-if="scope.row.machineStatus === 3" type="warning">重启中</el-tag>
          <el-tag v-else-if="scope.row.machineStatus === 4" type="warning">未开通</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80">
        <template slot-scope="scope">
          <el-button
            @click="setId(scope.row.id)"
            type="text"
            size="small">
            <span style="color: #409EFF;font-size: larger; font-weight: bold;">&hellip;</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.pageNum"
          :page-sizes="[4, 8, 12, 16]"
          :page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <div v-if="showDiv" class="fixed-div">
      <el-button @click="status=0;updateStatus()" icon="el-icon-caret-right" style="color: deepskyblue;margin:0 auto;border-style: none;margin-top: 30px"><font color="black">开通</font></el-button>
      <el-button @click="status=1;updateStatus()" icon="el-icon-remove-outline" style="color: red;margin:0 auto;border-style: none"><font color="black">禁用</font></el-button>
      <el-button @click="status=0;updateStatus()" icon="el-icon-caret-right" style="color: green;margin:0 auto;border-style: none"><font color="black">启用</font></el-button>
      <el-button @click="status=0;updateStatus()" icon="el-icon-loading" style="color: blue;margin:0 auto;border-style: none"><font color="black">重启</font></el-button>
      <el-button @click="status=2;updateStatus()" icon="el-icon-switch-button" style="color: red;margin:0 auto;border-style: none"><font color="black">关机</font></el-button>
      <el-button @click="status=0;updateStatus()" icon="el-icon-switch-button" style="color: green;margin:0 auto;border-style: none"><font color="black">开机</font></el-button>
    </div>
    <el-dialog title="添加柜机" :visible.sync="add">
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" style="width: 350px">
        <el-form-item label="柜机编码" prop="machineCode">
          <el-input v-model="addForm.machineCode" autocomplete="off" style="width: 270px"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" style="width: 300px" prop="location">
          <el-cascader
              placeholder="请选择地区"
              size="default"
              :options="options"
              v-model="location"
              @change="handleAddressChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addForm.address" autocomplete="off" style="width: 270px"></el-input>
        </el-form-item>
        <el-form-item label="设备型号" style="width: 300px" prop="isModel">
          <el-select v-model="addForm.isModel" placeholder="请选择">
            <el-option label="DOSON 32" value="DOSON 32"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="存藏类型" style="width: 300px" prop="storageStatus">
          <el-select v-model="addForm.storageStatus" placeholder="请选择">
            <el-option label="冷藏" value="1"></el-option>
            <el-option label="常温" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="MAC" prop="mac">
          <el-input v-model="addForm.mac" autocomplete="off" style="width: 245px"></el-input>
        </el-form-item>
        <el-form-item label="安装日期" style="width: 300px" prop="installDate">
          <el-date-picker
              v-model="addForm.installDate"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否开通" prop="machineStatus">
          <el-radio-group v-model="addForm.machineStatus">
            <el-radio :label="0">已开通</el-radio>
            <el-radio :label="4">未开通</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开通时间" prop="openDate" style="width: 300px">
          <el-date-picker :disabled="addForm.machineStatus===4"
              v-model="addForm.openDate"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="主柜尺寸">
          <el-input v-model="addForm.primaryWidth" autocomplete="off" style="width: 90px" placeholder="请填写宽"></el-input>
          <el-input v-model="addForm.primaryDepth" autocomplete="off" style="width: 90px" placeholder="请填写深"></el-input>
          <el-input v-model="addForm.primaryHeight" autocomplete="off" style="width: 90px" placeholder="请填写高"></el-input>
        </el-form-item>
        <el-form-item label="副柜尺寸">
          <el-input v-model="addForm.secondaryWidth" autocomplete="off" style="width: 90px" placeholder="请填写宽"></el-input>
          <el-input v-model="addForm.secondaryDepth" autocomplete="off" style="width: 90px" placeholder="请填写深"></el-input>
          <el-input v-model="addForm.secondaryHeight" autocomplete="off" style="width: 90px" placeholder="请填写高"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetAddForm();">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getList,updateStatus,addMachine} from "@/api/machine/VendingMachine";
import { regionData, codeToText } from 'element-china-area-data'

export default {
  name: "VendingMachine",
  data() {
    return {
      add: false,
      showDiv: false, // 控制 div 显示状态
      addForm:{
        machineCode:'',
        location:'',
        address:'',
        isModel:'',
        storageStatus:'',
        mac:'',
        installDate:'',
        machineStatus:'',
        openDate:'',
        primaryWidth:'',
        primaryDepth:'',
        primaryHeight:'',
        secondaryWidth:'',
        secondaryDepth:'',
        secondaryHeight:'',
      },
      location: [],
      options: regionData,
      status: 0,
      statusId:'',
      params: {
        date: '',
        dateTime: '',
      },
      total: 0,
      tableData: [],
      visible: false,
      searchForm: {
        ID:'',
        machineStatus:'',
        boxStatus:'',
        pageSize: 4,
        pageNum: 1,
      },
      addFormRules:{
        machineCode: [
          { required: true, message: '请输入柜机编码', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '请选择所在地区', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        isModel: [
          { required: true, message: '请选择设备型号', trigger: 'change' }
        ],
        storageStatus: [
          { required: true, message: '请选择存藏类型', trigger: 'change' }
        ],
        mac: [
          { required: true, message: '请输入MAC', trigger: 'blur' }
        ],
        installDate: [
          { required: true, message: '请填写安装日期', trigger: 'change' }
        ],
      }
    }
  },
  methods: {
    goToBoxDetail(val){
      this.$router.push({path: "/boxList", query: {id: val}});
    },
    routerAddMore(){
      this.$router.push({path: "/addMore"});
    },
    submitForm() {
      this.$refs.addForm.validate((valid)=> {
        if (valid) {
          this.addMachine();
        } else {
          console.error('表单验证失败!');
          return false;
        }
      });
    },
    addMachine() {
      if (this.addForm.machineStatus === 4){
        this.addForm.openDate = null;
      }
      addMachine(this.addForm).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '添加成功',
            type: 'success'
          });
          this.selectList();
          this.add = false;
          this.resetAddForm();
        } else {
          this.$message({
            message: '添加失败',
            type: 'error'
          });
        }
      }).catch(error => {
        console.error('提交失败:', error);
      });
    },
    handleAddressChange(value) {
      // 利用 map 获取对应文本并使用 join 将其连接为字符串
      this.location = value;
      // 使用 join 来拼接，并去除多余空格
      this.addForm.location = value.map(item => codeToText[item]).join('-').trim();
    },
    /*修改状态*/
    updateStatus(){
      if(this.statusId===''||this.statusId==null){
        this.$message({
          message: '请选择设备',
          type: 'warning'
        });
      }else{
        this.showDiv = !this.showDiv;
        this.$confirm('是否确认该操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const data = {
            id: this.statusId,
            machineStatus: this.status
          }
          updateStatus(data).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.statusId='';
              this.selectList();
            } else {
              this.$message({
                message: '操作失败',
                type: 'warning'
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      }
    },
    /*点击给要修改的id赋值*/
    setId(id) {
      this.statusId=id;
      this.showDiv = !this.showDiv;
    },
    /*规范时间格式*/
    formatDate(row, column) {
      // 获取单元格数据
      let data = row[column.property]
      if(data == null) {
        return null
      }
      let dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
    },
    formatDateTime(row, column) {
      // 获取单元格数据
      let data = row[column.property]
      if(data == null) {
        return null
      }
      let dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate() + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
    },
    /*关闭高级搜索*/
    closeSearch() {
      this.visible = false;
      this.params = {
        date: '',
        dateTime: '',
      }
      this.resetForm('searchForm');
      this.selectList();
    },
    /*分割时间 赋值*/
    dateFormat(picker) {
      if (Array.isArray(picker)){
        // 直接使用 ISO 格式的日期字符串
        this.searchForm.installStartDate = picker[0].slice(0, 10); // 截取 YYYY-MM-DD 部分
        this.searchForm.installEndDate = picker[1].slice(0, 10); // 截取 YYYY-MM-DD 部分
      }
    },
    dateTimeFormat(picker) {
      if (Array.isArray(picker)){
        this.searchForm.openStartDate = picker[0];
        this.searchForm.openEndDate = picker[1];
      }
    },
    /*搜索 表格展示*/
    selectList() {
      getList(this.searchForm).then(response => {
        this.tableData = response.data;
        this.total = response.total;
      });
    },
    /*动态分页*/
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.selectList();
    },
    handleCurrentChange(val) {
      this.searchForm.pageNum = val;
      this.selectList();
    },
    /*重置表单*/
    resetForm(formName) {
      this.params = {
        date: '',
        dateTime: '',
      }
      this.$refs[formName].resetFields();
    },
    /*重置添加表单*/
    resetAddForm() {
      this.addForm.machineStatus='';
      this.addForm.openDate='';
      this.addForm.primaryWidth='';
      this.addForm.primaryDepth='';
      this.addForm.primaryHeight='';
      this.addForm.secondaryWidth='';
      this.addForm.secondaryDepth='';
      this.addForm.secondaryHeight='';
      this.location=[];
      this.resetForm('addForm');
      this.add=false;
    },
    handleClick(id){
      this.$router.push({path: "/machineDetail", query: {id: id}});
    }
  },
  created() {
    this.selectList();
  }
}
</script>

<style scoped>
.fixed-div {
  position: fixed;
  top: 250px;  /* 距离窗口顶部20像素 */
  right: 10px; /* 距离窗口右侧20像素 */
  width: 100px;
  height: 300px;
  gap: 10px; /* 按钮之间的间距 */
  background-color: white;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
</style>
